// 引入网络请求工具类
import http from '../../../utils/https.js'

Page({
  data: {
    parkingOrders: [],  // 存储停车缴费订单信息
    loading: false      // 加载状态
  },

  onLoad() {
    // 页面加载时执行查询
    this.queryParkingOrders();
  },

  onShow() {
    // 页面显示时检查是否需要刷新数据
    const paymentSuccess = wx.getStorageSync('paymentSuccess');
    if (paymentSuccess) {
      // 清除支付成功标记
      wx.removeStorageSync('paymentSuccess');
      // 重新查询数据
      this.queryParkingOrders();
      console.log('支付成功，刷新订单数据');
    }
  },

  // 主流程：查询停车订单
  queryParkingOrders() {
    console.log('开始查询停车订单流程');
    this.setData({ loading: true });
    
    // 1. 从本地缓存获取residentId
    const residentId = wx.getStorageSync('residentId');
    
    if (!residentId) {
      console.error('未找到住户信息，residentId为空');
      wx.showToast({
        title: '未找到住户信息',
        icon: 'none',
        duration: 2000
      });
      this.setData({ loading: false });
      return;
    }
    
    console.log('获取到的residentId:', residentId);
    console.log('residentId类型:', typeof residentId);
    
    // 2. 调用车辆列表接口
    this.getVehiclesByResidentId(residentId)
      .then(vehicles => {
        console.log('查询到的车辆信息:', vehicles);
        console.log('车辆数组长度:', vehicles.length);
        
        if (!vehicles || vehicles.length === 0) {
          console.warn('该住户未绑定车辆');
          wx.showToast({
            title: '该住户未绑定车辆',
            icon: 'none',
            duration: 2000
          });
          this.setData({ loading: false });
          return Promise.reject('无车辆信息');
        }
        
        // 3. 为每辆车查询缴费订单，并根据sort字段过滤
        const parkingOrderPromises = vehicles.map(vehicle => {
          console.log('查询车辆ID:', vehicle.id, '的缴费订单，车辆类型sort:', vehicle.sort);
          
          // 如果sort=2（私家车），不显示该车辆的缴费订单
          if (vehicle.sort === 2) {
            console.log('车辆', vehicle.id, '为私家车(sort=2)，跳过查询缴费订单');
            return Promise.resolve([]);
          }
          
          return this.getParkingOrdersByVehicleId(vehicle.id)
            .then(orders => {
              // 为每个订单添加车辆信息
              return orders.map(order => ({
                ...order,
                vehicleInfo: vehicle
              }));
            })
            .catch(err => {
              console.error('查询车辆', vehicle.id, '的订单失败:', err);
              return [];
            });
        });
        
        // 4. 等待所有查询完成
        return Promise.all(parkingOrderPromises);
      })
      .then(allOrdersArrays => {
        // 5. 合并所有车辆的订单
        const allOrders = allOrdersArrays.flat();
        console.log('=============================');
        console.log('所有车辆的缴费订单信息如下:');
        console.log('总订单数量:', allOrders.length);
        console.log(allOrders);
        console.log('=============================');
        
        this.setData({ 
          parkingOrders: allOrders,
          loading: false 
        });
        
        if (allOrders.length === 0) {
          console.warn('未查询到缴费订单');
          wx.showToast({
            title: '未查询到缴费订单',
            icon: 'none',
            duration: 2000
          });
        } else {
          console.log('成功加载', allOrders.length, '个缴费订单');
        }
      })
      .catch(err => {
        console.error('操作失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: err.message || '查询失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 查询住户绑定的车辆
  getVehiclesByResidentId(residentId) {
    console.log('开始查询车辆，参数residentId:', residentId);
    
    return http.get('vehicle/vehicle/list', { residentId: residentId })
      .then(res => {
        console.log('车辆查询接口响应:', res);
        console.log('响应数据结构:', JSON.stringify(res, null, 2));
        
        // 检查接口返回状态
        if (res.code === 200 && res.rows) {
          console.log('提取的车辆数据:', res.rows);
          return res.rows;
        } else {
          console.warn('接口返回异常:', res);
          return [];
        }
      })
      .catch(err => {
        console.error('查询车辆失败:', err);
        console.error('错误详情:', JSON.stringify(err, null, 2));
        throw new Error(`查询车辆失败: ${err.message || '未知错误'}`);
      });
  },

  // 查询车辆的缴费订单
  getParkingOrdersByVehicleId(vehicleId) {
    console.log('开始查询停车订单，参数vehicleId:', vehicleId);
    
    return http.get('parkingPay/parkingPay/list', { vehicleId: vehicleId })
      .then(res => {
        console.log('停车订单查询接口响应:', res);
        console.log('响应数据结构:', JSON.stringify(res, null, 2));
        
        // 检查接口返回状态
        if (res.code === 200 && res.rows) {
          console.log('提取的停车订单数据:', res.rows);
          return res.rows;
        } else {
          console.warn('接口返回异常:', res);
          return [];
        }
      })
      .catch(err => {
        console.error('查询订单失败:', err);
        console.error('错误详情:', JSON.stringify(err, null, 2));
        throw new Error(`查询订单失败: ${err.message || '未知错误'}`);
      });
  },

  // 跳转到缴费页面
  gotoPayCar(e) {
    const orderData = e.currentTarget.dataset.order;
    
    // 检查订单状态
    if (orderData.paymentStatus === 0) {
      wx.showToast({
        title: '该订单已缴费',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 检查车辆类型
    if (orderData.vehicleInfo && orderData.vehicleInfo.sort === 1) {
      wx.showToast({
        title: '月卡车辆无需缴费',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (orderData) {
      // 将订单信息存储到本地缓存，供缴费页面使用
      wx.setStorageSync('currentParkingOrder', orderData);
    }
    
    // 跳转到缴费页面，并传递待交金额
    wx.navigateTo({
      url: `/service/pages/paycar/paycar?amount=${orderData.amount}`
    });
  },

  // 添加测试数据（开发测试用）
  addTestData() {
    console.log('添加测试数据');
    
    // 模拟不同车辆类型的测试数据
    const testData = [
      {
        id: 1,
        amount: 15.50,
        paymentStatus: 1,
        parkingTime: '2024-01-15 14:30:00',
        parkingDuration: 120,
        feeType: '临时停车',
        vehicleManagement: {
          plateNumber: '京A12345'
        },
        regionManagement: {
          regionName: 'A区停车场'
        },
        vehicleInfo: {
          id: 1,
          sort: 0, // 临时停车
          plateNumber: '京A12345'
        }
      },
      {
        id: 2,
        amount: 0,
        paymentStatus: 1,
        parkingTime: '2024-01-15 16:00:00',
        parkingDuration: 180,
        feeType: '月卡停车',
        vehicleManagement: {
          plateNumber: '京B67890'
        },
        regionManagement: {
          regionName: 'B区停车场'
        },
        vehicleInfo: {
          id: 2,
          sort: 1, // 月卡车辆
          plateNumber: '京B67890'
        }
      }
    ];
    
    this.setData({
      parkingOrders: testData,
      loading: false
    });
    
    wx.showToast({
      title: '测试数据已添加',
      icon: 'success',
      duration: 2000
    });
  }
});
